import moment from 'moment'
import cloud from 'wx-server-sdk'
import { ReturnReportResponse, SCFFaaSEvent, SCFHttpEvent } from './type'

cloud.init({
  env: (cloud as any).DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false,
} as any)

const db = cloud.database()

export async function main(event: SCFHttpEvent & SCFFaaSEvent) {
  console.log('请求参数：', event)


  /**
   * 问卷调查 Webhook
   */
  if (event?.httpMethod) {
    const router = new HttpRouter()
    return await router.handleRequest(event)
  }

  /**
   * 小程序调用云函数
   */
  const router = new FaaSRouter()
  return await router.handleInvoke(event)
}

class FaaSRouter {

  async handleInvoke(event: SCFFaaSEvent) {
    switch (event.method) {
      case 'anonymous_report':
        return this.handleAnonymousReport(event.data)
      case 'stat':
        return this.handleStat()
    }
  }

  async handleStat() {
    const context = cloud.getWXContext()
    const collection = db.collection('healthy_report')

    const count = await collection.where({ date: moment().format('yyyy-MM-DD hh:mm:ss') }).count()

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {
        count: (count as any)?.total,
        openId: context.OPENID
      }
    }
  }

  /**
   * 信息上报
   */
  handleAnonymousReport = async (content: string) => {
    const context = cloud.getWXContext()
    const collection = db.collection('anonymous_report')

    const data = {
      date: moment().format('yyyy-MM-DD hh:mm:ss'),
      openId: context.OPENID,
      content: content
    }

    await collection.add({ data })

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {}
    }
  }
}

class HttpRouter {

  handleRequest(event: SCFHttpEvent) {
    if (event?.httpMethod !== 'POST') {
      return {
        message: 'ok',
        status: 0,
        error: null,
        data: { event }
      }
    }

    const data = JSON.parse(event.body)

    switch (event.path) {
      case '/return_report':
        return this.handleReturnReport(data)
      case '/healthy_report':
        return this.handleHealthyReport(data)
    }
  }

  /**
   * 返校上报
   */
  handleReturnReport = async (body: ReturnReportResponse) => {
    /**
     * 字段及注释在 Typings 中
     */
    const { entry: {
      field_2,
      field_4,
      field_5,
      field_7,
      field_8,
      field_11,
      field_12,
      field_13,
      field_14,
    } }: ReturnReportResponse = body

    const data = {
      name: field_2,
      phone: field_4,
      return_date: field_5,
      transportation: field_7,
      transportation_info: field_8,
      city_footprint: field_11,
      wuhan: field_12 === '是',
      touch_wuhan: field_13 === '是',
      status: field_14,
      date: moment().format('yyyy-MM-DD hh:mm:ss'),
    }

    const collection = db.collection('return_report')

    const result = await collection
      .where({ name: field_2, phone: field_4, })
      .get()

    if (result.data.length === 0) {
      await collection.add({ data })
    } else {
      await collection
        .where({ name: field_2, phone: field_4, })
        .update({ data })
    }

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {}
    }
  }


  handleHealthyReport = async (body) => {
    // 校园信息
    if (!body?.entry?.field_1) {
      return
    }

    const data = {
      date: moment().format('yyyy-MM-DD hh:mm:ss'),
      ...body,
    }

    const collection = db.collection('healthy_report')
    await collection.add({ data })

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {}
    }
  }
}
